<template>
    <div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>

            <el-form-item label="分类名称" prop="activityName">
                <el-input v-model="ruleForm.activityName" />
            </el-form-item>
            <el-form-item label="分类图片" prop="activityPhoto">
                <div v-if="ruleForm.activityPhoto" style="position: relative; width: 178px;
  height: 178px;">
                    <img :src="ruleForm.activityPhoto" class="avatar" />
                    <el-icon
                        style="position: absolute;top: 10px;right: 10px;cursor: pointer;color: red;font-size: 24px;"
                        @click="removeImg">
                        <CircleClose />
                    </el-icon>
                </div>
                <el-upload v-else class="avatar-uploader" action="#" :show-file-list="false"
                    :before-upload="beforeAvatarUpload">
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="状态" prop="activityStatus">
                <el-radio-group v-model="ruleForm.activityStatus" class="ml-4">
                    <el-radio label="0" size="large">开启</el-radio>
                    <el-radio label="1" size="large">关闭</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确认
                </el-button>
                <el-button @click="closeAdd()">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import { deletePhoto } from '@/api/merchant.js'
import { activityClassificationAdd, activityClassificationUpdate } from '@/api/activity.js'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['closeAdd', 'closeOK'])
const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = reactive({
    activityName: '',
    activityStatus: '1',
    activityPhoto: '',
})

const rules = reactive(
    {
        activityName: [
            { required: true, message: '请输入', trigger: 'blur' },
        ],
        activityPhoto: [
            { required: true, message: '请选择', trigger: 'change' },
        ],
        activityStatus: [
            { required: true, message: '请选择', trigger: 'change' },
        ],
    })



const props = defineProps({
    isAdd: {
        type: Boolean,
        default: false,
    },
    row: {
        type: Object,
        default: () => ({}), // 默认值为一个空对象
    },
})
onMounted(() => {
    if (!props.isAdd) {
        ruleForm.activityName = props.row.activityName; // 初始化表单字段值
        ruleForm.activityStatus = props.row.activityStatus; // 初始化表单字段值
        ruleForm.activityPhoto = props.row.activityPhoto; // 初始化表单字段值
    }
})
// 文件上传
const beforeAvatarUpload = (file) => {
    const formData = new FormData(); // 创建FormData对象用于发送表单数据
    formData.append('file', file); // 将文件添加到FormData对象中，键名为'file'（根据后端需求）
    console.log(file);
    axios.post(`${import.meta.env.VITE_APP_API}/commonUtil/addPhoto`, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': localStorage.getItem('satoken'),
            'satoken': localStorage.getItem('satoken')
        } // 设置正确的Content-Type头部信息
    }).then(response => {
        ruleForm.activityPhoto = response.data.data;
        console.log('File uploaded successfully:', response); // 上传成功后的处理逻辑
    }).catch(error => {
        console.error('Error uploading file:', error); // 上传失败后的处理逻辑
    });
    return false; // 返回false阻止文件上传
}
// 删除头像
const removeImg = () => {
    let filename = ruleForm.activityPhoto.split('/').pop(); // 提取文件名部分
    deletePhoto({ filename }).then(response => {
        ruleForm.activityPhoto = ''; // 清空图片activityPhoto
        console.log('File deleted successfully:', response); // 删除成功后的处理逻辑 
    })
}

// 确认
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (props.isAdd) {
                activityClassificationAdd(ruleForm).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '添加成功',
                        })
                        emit('closeOK')
                    }
                })

            } else {
                activityClassificationUpdate({ ...ruleForm, id: props.row.id }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '修改成功',
                        })
                        emit('closeOK')
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 关闭
const closeAdd = () => {
    emit('closeAdd')
}
</script>

<style lang="scss" scoped>
.avatar {
    width: 100%;
    height: 100%;
}

::v-deep .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

::v-deep.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

::v-deep .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>